package com.hyt.it.ogt.kq.service.gov.service.impl;

import java.io.IOException;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.hyt.core.base.BaseServiceImpl;
import com.hyt.core.util.UUIDUtils;
import com.hyt.it.ogt.kq.common.config.ConfigManager;
import com.hyt.it.ogt.kq.common.config.exception.KqException;
import com.hyt.it.ogt.kq.common.gov.constant.CodeEnum;
import com.hyt.it.ogt.kq.common.gov.constant.ResponseCode;
import com.hyt.it.ogt.kq.common.gov.utils.Constants;
import com.hyt.it.ogt.kq.service.gov.mapper.OfficeFileTemplateMapper;
import com.hyt.it.ogt.kq.service.gov.model.entity.OfficeFileTemplate;
import com.hyt.it.ogt.kq.service.gov.model.entity.SysFile;
import com.hyt.it.ogt.kq.service.gov.model.param.OfficeFileTemplateParam;
import com.hyt.it.ogt.kq.service.gov.service.IOfficeFileTemplateService;
import com.hyt.it.ogt.kq.service.gov.service.ISysFileService;
import com.hyt.it.ogt.kq.service.gov.service.obs.CloudObsService;

/**
 * <p>
 * 模板文件参数表 服务实现类
 * </p>
 *
 * @author huangyh
 * @since 2021-09-02
 */
@Service
public class OfficeFileTemplateServiceImpl extends BaseServiceImpl<OfficeFileTemplateMapper, OfficeFileTemplate>
        implements IOfficeFileTemplateService {
    public static final String TEMPLATE = "template";
    public static final String DEFAULT_OFFICE_ID = "0";

    @Resource
    private CloudObsService cloudObsService;
    @Resource
    private ConfigManager configManager;
    @Resource
    private ISysFileService iSysFileService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(MultipartFile file, OfficeFileTemplateParam param) throws IOException {
        String path = null;
        try {
            path = StringUtils.join(configManager.getCloudRootPath(), TEMPLATE, "/", param.getType(), "/",
                    file.getOriginalFilename());
            // 考试协议包上传到云存储
            String url = cloudObsService.updateFile(path, file.getInputStream());

            SysFile sysFile = new SysFile();
            sysFile.setName(file.getOriginalFilename()).setPath(path).setType(param.getType()).setUrl(url);
            iSysFileService.save(sysFile);

            OfficeFileTemplate entity = new OfficeFileTemplate();
            // 复制属性
            BeanUtils.copyProperties(param, entity);

            entity.setFileId(sysFile.getId());
            try {
                if (entity.getLevel() <= Constants.OFFICE_LEVEL_MIN || entity.getLevel() > Constants.OFFICE_LEVEL_MAX) {
                    throw new KqException(ResponseCode.OFFICE_FILE_TEMPLATE_LEVEL_WRONG.getCode(),
                            ResponseCode.OFFICE_FILE_TEMPLATE_LEVEL_WRONG.getMsg());
                }
                if (entity.getLevel().equals(CodeEnum.SYSTEM_DATA.getCode())) {
                    entity.setOfficeId(DEFAULT_OFFICE_ID);
                }
                super.save(entity);
            } catch (DuplicateKeyException e) {
                throw new KqException(ResponseCode.OFFICE_FILE_TEMPLATE_EXIST.getCode(),
                        ResponseCode.OFFICE_FILE_TEMPLATE_EXIST.getMsg());
            }
        } catch (Exception e) {
            if(path != null) {
                cloudObsService.deleteFile(path);
            }
            throw e;
        }
    }

    @Override
    public String getUrl(String officeId, String type, String code) {
        String url = baseMapper.getUrl(officeId, type, code, CodeEnum.OFFICE_DATA.getCode());
        // 没有就用系统默认级别
        if(StringUtils.isBlank(url)) {
            // 系统级别默认officeId是0
            url = baseMapper.getUrl(DEFAULT_OFFICE_ID, type, code, CodeEnum.SYSTEM_DATA.getCode());
        }
        return url;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add2(MultipartFile file, String taskId,String officeId) throws IOException {
        String path = null;
        try {

            String code = "breakRule";

            path = StringUtils.join(configManager.getCloudRootPath(), TEMPLATE, "/", code, "/",
                    file.getOriginalFilename());
            // 考试协议包上传到云存储
            String url = cloudObsService.updateFile(path, file.getInputStream());

            SysFile sysFile = new SysFile();
            sysFile.setName(file.getOriginalFilename()).setPath(path).setType(code).setUrl(url);
            iSysFileService.save(sysFile);

            OfficeFileTemplate entity = new OfficeFileTemplate();
            entity.setFileId(sysFile.getId())
                    .setCode(code)
                    .setOfficeId(officeId)
                    .setType(code)
                    .setLabel("违纪信息模板")
                    .setLevel(1)
                    .setDelFlag(false)
                    .setId(UUIDUtils.newSortUUID());

            try {
                if (entity.getLevel() <= Constants.OFFICE_LEVEL_MIN || entity.getLevel() > Constants.OFFICE_LEVEL_MAX) {
                    throw new KqException(ResponseCode.OFFICE_FILE_TEMPLATE_LEVEL_WRONG.getCode(),
                            ResponseCode.OFFICE_FILE_TEMPLATE_LEVEL_WRONG.getMsg());
                }
                if (entity.getLevel().equals(CodeEnum.SYSTEM_DATA.getCode())) {
                    entity.setOfficeId(DEFAULT_OFFICE_ID);
                }
                super.save(entity);
            } catch (DuplicateKeyException e) {
                throw new KqException(ResponseCode.OFFICE_FILE_TEMPLATE_EXIST.getCode(),
                        ResponseCode.OFFICE_FILE_TEMPLATE_EXIST.getMsg());
            }
        } catch (Exception e) {
            if(path != null) {
                cloudObsService.deleteFile(path);
            }
            throw e;
        }
    }

}
